package com.tanhua.sso.controller;

import com.tanhua.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("loginVerification")
    public ResponseEntity<Object> loginVerification(@RequestBody Map<String,String> param){

        Map<String, String> map = null;

        try {
            ErrorResult errorResult;
            //拿到手机号和验证码
            String phone = param.get("phone");
            String verificationCode = param.get("verificationCode");

            //TODO 验证验证码的有效性, 传入手机号和验证码, 应该返回什么?
            // 验证码正确, 但是手机号在mysql中不存在 --> 执行注册动作, 返回token和isNew:true
            // 验证码正确, 但是手机号在mysql中已经存在 --> 执行登录动作, 返回token和isNew:false
            // 验证码错误, 返回null
            // 验证码过期, 返回null
            map = userService.loginVerification(phone,verificationCode);

            if (null == map){
                errorResult = ErrorResult.builder().errCode("000002").errMessage("验证码错误, 登录失败!").build();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(map);
    }

    /**
     * 校验token，根据token查询用户数据
     *
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }
}
